<template>
  <div class="favortree-container">
    <div class="top-button" @click="showAddOrEditGroupDialog()">
      <span class="el-icon-plus"></span>
      <span>添加分组</span>
    </div>
    <el-tree
      :data="groupFavorData"
      :props="defaultProps"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <el-tooltip :content="node.label" placement="top">
          <span class="tree-node-label">{{
            node.label + getNodeStatic(data)
          }}</span>
        </el-tooltip>
        <span>
          <el-tooltip content="定位" placement="top">
            <span
              v-if="data.nodeType === 'ship'"
              class="el-icon-aim tree-node-btn"
              @click="locateShip(node)"
            ></span>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <span
              v-if="data.groupType === 'othor'"
              class="el-icon-edit-outline tree-node-btn"
              @click="showAddOrEditGroupDialog(node)"
            ></span>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <span
              v-if="data.nodeType === 'ship' && !data.isMyShip"
              class="el-icon-edit-outline tree-node-btn"
              @click="showEditShipCustomNameDialog(node)"
            ></span>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <span
              v-if="
                data.groupType != 'my' &&
                data.groupType != 'default' &&
                !data.isMyShip
              "
              class="el-icon-delete tree-node-btn"
              @click="() => remove(node, data)"
            ></span>
          </el-tooltip>
        </span>
      </span>
    </el-tree>
    <el-dialog
      title="删除分组"
      :visible.sync="delGroupDialogShow"
      :append-to-body="true"
      :close-on-click-modal="false"
      :modal="true"
      :center="true"
      width="400px"
      custom-class="shipping-online-dialog"
    >
      <div>
        <el-radio v-model="groupDelType" label="0">
          解散分组，将组内船舶移至默认分组
        </el-radio>
      </div>
      <div class="dialog-radio2">
        <el-radio v-model="groupDelType" label="1">
          删除分组及组内船舶
        </el-radio>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="delGroupDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="doDeleteGroup"> 确 定 </el-button>
      </span>
    </el-dialog>

    <el-dialog
      ref="addOrEditGroupForm"
      :title="groupForm.node ? '修改分组' : '添加分组'"
      :visible.sync="addOrEditGroupShow"
      :append-to-body="true"
      :close-on-click-modal="false"
      :modal="true"
      width="400px"
      custom-class="shipping-online-dialog"
    >
      <el-form
        ref="groupForm"
        :model="groupForm"
        :rules="groupFormRules"
        label-width="100px"
      >
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupForm.name" maxlength="20"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelClickEditGroupShow">取 消</el-button>
        <el-button type="primary" @click="saveGroupInfo"> 确 定 </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改自定义船名"
      :visible.sync="editCustomShipNameShow"
      :append-to-body="true"
      :close-on-click-modal="false"
      :modal="true"
      width="450px"
      custom-class="shipping-online-dialog"
      :destroy-on-close="true"
    >
      <el-form
        ref="shipForm"
        :model="shipForm"
        :rules="shipFormRules"
        label-width="100px"
      >
        <el-form-item label="自定义名称" prop="name">
          <el-input v-model="shipForm.name"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="shipForm.remark"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editCustomShipNameShow = false">取 消</el-button>
        <el-button type="primary" @click="saveShipCustomName">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  addFavorGroup,
  editFavorGroupName,
  cancelShipFavor,
  editFavorShipCustomName,
  delFavorGroup,
  getFavorList,
} from "@/api/shipGroup";
export default {
  data() {
    return {
      groupFavorData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      delGroupDialogShow: false,
      groupDelType: "1",
      groupNodeToRemove: undefined,

      addOrEditGroupShow: false,
      groupForm: {
        node: undefined,
        name: "",
      },
      groupFormRules: {
        name: [
          {
            required: true,
            message: "请输入分组名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      editCustomShipNameShow: false,
      shipForm: {
        node: undefined,
        name: "",
        remark: "",
      },
      shipFormRules: {
        name: [
          {
            required: true,
            message: "请输入自定义名称",
            trigger: "blur",
          },
          {
            max: 20,
            message: "长度在 20 个字符以内",
            trigger: "blur",
          },
        ],
        remark: [
          {
            max: 100,
            message: "长度在 100 个字符以内",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    delGroupDialogShow: function (val, oldVal) {
      // 删除分组弹框关闭后，重置弹框数据
      if (!val) {
        this.groupDelType = "0";
        this.groupNodeToRemove = undefined;
      }
    },
    addOrEditGroupShow: function (val, oldVal) {
      if (!val) {
        this.groupForm.node = undefined;
        this.groupForm.name = "";
      }
    },
    editCustomShipNameShow: function (val, oldVal) {
      if (!val) {
        this.shipForm.node = undefined;
        this.shipForm.name = "";
        this.shipForm.remark = "";
      }
    },
  },
  mounted() {
    this.loadFavorTree();
  },
  destroy() {},
  methods: {
    loadFavorTree() {
      getFavorList().then((res) => {
        if (res.result && res.result.length > 0) {
          const favorShips = [];
          this.groupFavorData = res.result.map((val) => {
            const nodeData = {
              label: val.groupName,
              id: val.id ? val.id : "wodechuanbo__",
              nodeType: "group",
              groupType: "othor",
            };
            // 我的船舶
            if (!val.id) {
              nodeData.groupType = "my";
            }
            // 默认分组
            if (!val.userId && val.id) {
              nodeData.groupType = "default";
            }
            if (val.myCollectionShips && val.myCollectionShips.length > 0) {
              nodeData.children = val.myCollectionShips.map((ship) => {
                if (nodeData.groupType != "my") {
                  favorShips.push(ship.shipId);
                }
                return {
                  label: ship.customShipName,
                  id: "ship_" + ship.shipId,
                  dataId: ship.id,
                  shipId: ship.shipId,
                  nodeType: "ship",
                  remark: ship.remark,
                  isMyShip: nodeData.groupType == "my",
                };
              });
            }

            return nodeData;
          });
          this.$emit("favor-changed", favorShips);
        }
      });
    },
    handleNodeClick(data) {},
    // 获取节点统计信息
    getNodeStatic(node) {
      let count;
      if (node.children) {
        count = node.children.length ? node.children.length : 0;
      }
      if (count >= 0) {
        return `（${count}）`;
      }
      return "";
    },
    // 取消关注船舶
    removeShipFavor(node, data) {
      this.$confirm("确定不再关注该船舶?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        cancelShipFavor(data.shipId).then((res) => {
          if (res.success) {
            this.$message.success("取消关注成功！");
            this.loadFavorTree();
          } else {
            this.$message.success("取消关注失败！");
          }
        });
      });
    },
    // 删除分组
    removeGroup(node, data) {
      this.delGroupDialogShow = true;
      this.groupNodeToRemove = { node, data };
    },
    // 执行删除分组
    doDeleteGroup() {
      if (this.groupNodeToRemove) {
        const node = this.groupNodeToRemove.node;
        const data = this.groupNodeToRemove.data;

        delFavorGroup(data.id, this.groupDelType).then((res) => {
          if (res.success) {
            this.$message.success("删除分组成功！");
            this.loadFavorTree();
          } else {
            this.$message.success("删除分组失败！");
          }
        });
      }

      this.delGroupDialogShow = false;
    },

    // 树节点移除
    remove(node, data) {
      if (data.nodeType === "ship") {
        this.removeShipFavor(node, data);
      } else {
        this.removeGroup(node, data);
      }
    },
    showAddOrEditGroupDialog(node) {
      if (node) {
        this.groupForm.node = node;
        this.groupForm.name = node.data.label;
      }
      this.addOrEditGroupShow = true;
    },
    showEditShipCustomNameDialog(node) {
      this.shipForm.node = node;
      this.shipForm.name = node.data.label;
      this.shipForm.remark = node.data.remark;
      this.editCustomShipNameShow = true;
    },

    // 保存分组信息
    saveGroupInfo() {
      this.$refs["groupForm"].validate((valid) => {
        if (valid) {
          const node = this.groupForm.node;

          // 修改分组
          if (node) {
            editFavorGroupName({
              id: this.groupForm.node.data.id,
              groupName: this.groupForm.name,
            }).then((res) => {
              if (res.success) {
                this.$message.success("修改分组成功！");
                this.loadFavorTree();
              } else {
                this.$message.success("修改分组失败！");
              }
            });
          } else {
            addFavorGroup({ groupName: this.groupForm.name }).then((res) => {
              if (res.success) {
                this.$message.success("添加分组成功！");
                this.loadFavorTree();
              } else {
                this.$message.success("添加分组失败！");
              }
            });
          }

          this.addOrEditGroupShow = false;
        }
      });
    },
    saveShipCustomName() {
      this.$refs["shipForm"].validate((valid) => {
        if (valid) {
          editFavorShipCustomName({
            id: this.shipForm.node.data.dataId,
            customShipName: this.shipForm.name,
            remark: this.shipForm.remark,
          }).then((res) => {
            if (res.success) {
              this.$message.success("修改船舶自定义名称成功！");
              this.loadFavorTree();
            } else {
              this.$message.success("修改船舶自定义名称失败！");
            }
          });

          this.editCustomShipNameShow = false;
        }
      });
    },
    locateShip(node) {
      this.$emit("locate-ship", node.data.shipId);
    },
    cancelClickEditGroupShow() {
      this.$refs.groupForm.resetFields();
      this.addOrEditGroupShow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .tree-node-btn {
    padding: 0 4px 0 4px;
  }
  .tree-node-label {
    max-width: 162px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
// @mixin scrollBar() {
//   &::-webkit-scrollbar-track-piece {
//     background: #d3dce6;
//   }
//   &::-webkit-scrollbar-thumb {
//     background: #99a9bf;
//     border-radius: 20px;
//   }
//   &::-webkit-scrollbar {
//     width: 6px;
//     height: 10px;
//   }
// }
.favortree-container {
  padding: 10px;
  max-height: 480px;
  overflow: auto;
  &::-webkit-scrollbar-track-piece {
    background: #ffffff;
  }
  &::-webkit-scrollbar-thumb {
    background: #ebeef5;
    border-radius: 20px;
  }
  &::-webkit-scrollbar {
    width: 4px;
    height: 10px;
  }
  .top-button {
    padding: 0 0 10px 10px;
    cursor: pointer;
    span {
      font-size: 12px;
      font-weight: 400;
      color: #004aaa;
    }
  }
  .dialog-radio2 {
    margin-top: 10px;
  }
}
</style>
